package com.driving.code.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA.
 * 作者: 喜欢编程的代先生
 * 日期: 2021/5/28
 * 时间: 21:21
 * 内容: Shiro与springboot整合教程！
 * 描述: 全局异常处理类
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler
    public String doException(Exception e){

        if (e instanceof UnknownAccountException){
            //当前抛出的异常是 用户名不存在
            return "2";
        }

        if (e instanceof IncorrectCredentialsException){
            //当前捕获的异常是 密码不正确
            SecurityUtils.getSubject().logout();
            return "1";
        }

        if (e instanceof AuthorizationException){
            //当前捕获的异常是 没有权限
            return "3";
        }
        return "error";
    }

}
